"""
肝脏参数计算 - 主程序
"""
import os
import pandas as pd
import numpy as np  # 添加这行导入NumPy
from liver_calculator import LiverParametersCalculator

def main():
    # 创建肝脏参数计算器
    calculator = LiverParametersCalculator()
    
    try:
        # 读取人口统计学数据(包含BSA和年龄)
        input_file_path = r"C:\Users\27135\Desktop\population\封装\Demographics\src\module1\Uniform_demographics.csv"
        
        # 确保输出目录存在
        output_directory = r"C:\Users\27135\Desktop\population\封装\Liver"
        if not os.path.exists(output_directory):
            os.makedirs(output_directory)
        
        # 定义输出文件路径
        output_file_path = os.path.join(output_directory, "liver_parameters.csv")
        
        # 打印计算公式摘要
        print("===== 肝脏参数计算公式 =====")
        formulas = calculator.get_formula_summary()
        for name, formula in formulas.items():
            print(f"{name}: {formula}")
            
        print("\n===== 计算参数汇总 =====")
        print("肝脏体积参数:")
        for k, v in calculator.liver_volume_params.items():
            print(f"  - {k}: {v}")
            
        print("\nHPGL参数:")
        for k, v in calculator.hpgl_params.items():
            print(f"  - {k}: {v}")
            
        print("\nMPPGL参数:")
        for k, v in calculator.mppgl_params.items():
            print(f"  - {k}: {v}")
            
        print("\nCPPGL参数:")
        for k, v in calculator.cppgl_params.items():
            print(f"  - {k}: {v}")
            
        print("\nS9PPGL参数:")
        for k, v in calculator.s9ppgl_params.items():
            print(f"  - {k}: {v}")
        
        if os.path.exists(input_file_path):
            print(f"\n读取数据: {input_file_path}")
            demographic_data = pd.read_csv(input_file_path)
            
            # 设置一个变量来存储随机种子
            random_seed = 42  # 定义random_seed变量
            
            # 处理数据(固定随机种子以便结果可重现)
            results = calculator.process_demographic_data(
                demographic_data, 
                bsa_column='BSA (m2)', 
                age_column='Age(years)',
                random_seed=random_seed  # 使用定义的变量
            )
            
            # 计算并打印结果统计信息
            mean_volume = results['Liver_Volume_L'].mean()
            mean_weight = results['Liver_Weight_g'].mean()
            mean_hpgl = results['HPGL_10e6_cells_per_g'].mean()
            mean_mppgl = results['MPPGL_mg_per_g'].mean()
            mean_cppgl = results['CPPGL_mg_per_g'].mean()
            mean_s9ppgl = results['S9PPGL_mg_per_g'].mean()
            
            cv_volume = (results['Liver_Volume_L'].std() / mean_volume) * 100
            cv_hpgl = (results['HPGL_10e6_cells_per_g'].std() / mean_hpgl) * 100
            cv_mppgl = (results['MPPGL_mg_per_g'].std() / mean_mppgl) * 100
            cv_cppgl = (results['CPPGL_mg_per_g'].std() / mean_cppgl) * 100
            cv_s9ppgl = (results['S9PPGL_mg_per_g'].std() / mean_s9ppgl) * 100
            
            print("\n===== 计算结果统计 =====")
            print(f"样本数量: {len(results)}")
            print(f"平均肝脏体积: {mean_volume:.3f} L (CV: {cv_volume:.1f}%)")
            print(f"平均肝脏重量: {mean_weight:.1f} g")
            print(f"平均HPGL: {mean_hpgl:.2f} × 10^6 cells/g (CV: {cv_hpgl:.1f}%)")
            print(f"平均MPPGL: {mean_mppgl:.2f} mg/g (CV: {cv_mppgl:.1f}%)")
            print(f"平均CPPGL: {mean_cppgl:.2f} mg/g (CV: {cv_cppgl:.1f}%)")
            print(f"平均S9PPGL: {mean_s9ppgl:.2f} mg/g (CV: {cv_s9ppgl:.1f}%)")
            
            # 保存结果到指定位置
            results.to_csv(output_file_path, index=False)
            print(f"\n结果已保存至: {output_file_path}")
            
            # 显示前几行数据
            print("\n数据预览:")
            preview_columns = ['ID', 'Age(years)', 'BSA (m2)', 'Liver_Volume_L', 
                              'Liver_Weight_g', 'HPGL_10e6_cells_per_g', 'MPPGL_mg_per_g',
                              'CPPGL_mg_per_g', 'S9PPGL_mg_per_g']
            print(results[preview_columns].head())
            
            # 显示不同年龄的计算值示例
            print("\n不同年龄的参数计算示例:")
            for age in [0.5, 5, 20, 28, 40, 60, 80]:
                # 重置随机种子以确保可重复性
                if random_seed is not None:
                    np.random.seed(random_seed + int(age))
                
                # 计算基础值和变异值
                base_hpgl = calculator.hpgl_params['baseline']
                hpgl = calculator.calculate_hpgl(age)
                base_mppgl = calculator.mppgl_params['mean']
                mppgl = calculator.calculate_mppgl(age)
                base_cppgl = calculator.cppgl_params['baseline'] + calculator.cppgl_params['slope'] * base_mppgl
                cppgl = calculator.calculate_cppgl(mppgl)
                s9ppgl = calculator.calculate_s9ppgl(mppgl, cppgl)
                
                print(f"年龄 {age} 岁:")
                print(f"  - HPGL(含变异): {hpgl:.2f} × 10^6 cells/g")
                print(f"  - MPPGL(含变异): {mppgl:.2f} mg/g")
                print(f"  - CPPGL(含变异): {cppgl:.2f} mg/g")
                print(f"  - S9PPGL: {s9ppgl:.2f} mg/g")
            
        else:
            print(f"错误: 文件不存在 - {input_file_path}")
    
    except Exception as e:
        print(f"处理数据时出错: {str(e)}")

if __name__ == "__main__":
    main()
